<template>
  <basic-container>
    <div>
      <m-s-search
        @searchClick="
          (v) => {
            (queryForm = v), getPage();
          }
        "
        :list="eventManageOption.column"
      >
      </m-s-search>
    </div>
    <avue-crud
      :option="eventManageOption"
      :data="tableData"
      ref="crud"
      @current-change="currentChange"
      @size-change="sizeChange"
      :page.sync="page"
    >
      <template slot="isSync" slot-scope="{ row }">
        {{ row.isSync === 0 ? "同步" : "异步" }}
      </template>
      <template slot="executorRouteStrategy" slot-scope="{ row }">
        {{ getRuleDetail(row.executorRouteStrategy) }}
      </template>
      <template slot="id" slot-scope="{ row }">
        <el-button
          type="text"
          @click.native="addToTabsList('事件', row, 'eventManageTemp', 'view')"
          >{{row.id}}</el-button
        >
      </template>
      <template slot="state" slot-scope="{ row }">
        {{ Number(row.state) === 1 ? "禁用" : "启用" }}
      </template>
      <template slot="menuLeft" slot-scope="{ size }">
        <div class="header-search">
          <el-button
            :size="size"
            type="primary"
            @click.native="addToTabsList('事件', {}, 'eventManageTemp', 'open')"
          >
            新增事件
          </el-button>
        </div>
      </template>
      

      <template slot="menu" slot-scope="{ row }">
        <el-button
          type="text"
          @click.native="addToTabsList('事件', row, 'eventManageTemp', 'edit')"
          >编辑</el-button
        >
        <el-button type="text" @click.native="subscribe(row)">订阅</el-button>
        <el-button type="text" :disabled="!row.executorHandler" @click.native="send(row)"
          >发送</el-button
        >
        <el-button type="text" @click.native="changeEnable(row)"
          >{{ Number(row.state) === 0 ? "禁用" : "启用" }}</el-button
        >
        <!-- <el-button
          type="text"
          v-if="row.isSync !== 0"
          @click.native="release(row)"
          >释放</el-button
        > -->
           <el-button
          type="text"
           @click.native="searchLog(row)"
          >日志</el-button
        >
      </template>
    </avue-crud>
    <ms-drawer
      @refresh="getPage()"
      :visible.sync="visible"
      :tab-list.sync="tabsList"
    ></ms-drawer>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="triggerVisible"
      append-to-body
    >
      <div v-if="dialogType === 'send'">
        <el-form :model="form" ref="triggerForm">
          <el-form-item label="方法参数" :label-width="formLabelWidth" props="">
            <el-col :span="20">
              <!-- <el-input
                v-model="triggerForm.executorParam"
                type="textarea"
              ></el-input> -->
              <code-editor
                :mode="'javascript'"
                v-model="triggerForm.executorParam"
                ref="ecEditor"
              ></code-editor>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="dialogType === 'subscribe'">
        <el-form :model="form" ref="triggerForm">
          <el-form-item label="服务名称" prop="jobGroup">
            <el-select
              v-model="triggerForm.jobGroup"
              multiple
              @change="changeService"
            >
              <el-option
                v-for="item in serverList"
                :key="item.id"
                :label="item.appname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方法编码" prop="executorHandler">
            <el-select
              v-model="triggerForm.executorHandler"
              placeholder="请输入关键词"
              :loading="loading"
              multiple
              filterable
              remote
              :remote-method="remoteMethod"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-if="dialogType">
        <el-button @click="triggerVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTrigger">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button @click="triggerVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="subscribeVisible"
      append-to-body
    >
      <div>
        <el-form :model="form" ref="triggerForm">
          <el-form-item label="服务名称" prop="jobGroup">
            <el-select
              v-model="triggerForm.jobGroup"
              multiple
              @change="changeService"
            >
              <el-option
                v-for="item in serverList"
                :key="item.id"
                :label="item.appname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方法编码" prop="executorHandler">
            <el-select
              v-model="triggerForm.executorHandler"
              placeholder="请输入关键词"
              :loading="loading"
              multiple
              filterable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="subscribeVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTrigger">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import MSSearch from "@/DMDComponents/MSSearch.vue";
import CodeEditor from "@/components/code-editor/index";
import * as taskManageApi from "@/api/taskManage/taskManage";
import * as api from "@/api/eventManage/index";

export default {
  name: "eventManage",
  components: {
    MSSearch,
    CodeEditor,
  },
  inject: ["eventManageOption"],
  data() {
    return {
      tableData: [],
      selection: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      formLabelWidth: 100,
      queryForm: {},
      currentData: {},
      triggerForm: {
        jobGroup: [],
      },
      dialogTitle: "",
      tabsList: [],
      serverList: [],
      visible: false,
      triggerVisible: false,
      subscribeVisible: false,
      dialogType: "send",
      routeList: [
        {
          label: "第一个",
          value: "FIRST",
        },
        {
          label: "最后一个",
          value: "LAST",
        },
        {
          label: "单-轮询",
          value: "ROUND",
        },
        {
          label: "单-随机",
          value: "RANDOM",
        },
        {
          label: "故障转移",
          value: "FAILOVER",
        },
        {
          label: "忙碌转移",
          value: "BUSYOVER",
        },
        {
          label: "一致性哈希",
          value: "CONSISTENT_HASH",
        },
        {
          label: "最不经常使用",
          value: "LEAST_FREQUENTLY_USED",
        },
        {
          label: "最近最久未使用",
          value: "LEAST_RECENTLY_USED",
        },
        {
          label: "全部",
          value: "SHARDING_BROADCAST",
        },
      ],
    };
  },
  methods: {
    getRuleDetail(val){
      if(!val){
        return ''
      }
      const [selected] = this.routeList.filter(v=>v.value ===val);
      return selected ? selected.label : ''

    },
    changeEnable(row){
      const that = this;
      const title = Number(row.state) === 0 ? "禁用" : "启用";
      // this.designer.dataSource.splice(idx, 1);
      this.$confirm(`确认${title}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log('66666666')
          api.changeState({ id: row.id,state:Number(row.state) === 0 ? 1:0  }).then((res) => {
            this.$message({
              type: "success",
              message: `${title}成功!`,
            });
            that.getPage();
          });
        })
        .catch(() => {});
    },
    searchLog(row) {
      this.$router.push({
        path: "/eventManage/eventManageLog",
        query: {
          eventId: row.id,
        },
      });
    },
    changeService(val) {
      this.triggerForm.jobGroup = val;
      this.remoteMethod();
    },
    remoteMethod(query) {
      let params = {};
      if (typeof query === "string" && !!query) {
        params = {
          jobGroups: this.triggerForm.jobGroup.join(","),
          methodName: query,
          start: 1,
          length: 100,
        };
      } else {
        params = {
          jobGroups: this.triggerForm.jobGroup.join(","),
          start: 1,
          length: 100,
        };
      }
      taskManageApi.getMethodLists({ ...params }).then((res) => {
        this.loading = false;
        this.options = res.data.map((v) => ({ label: v, value: v }));
        this.subscribeVisible = true;
      });
    },
    getServiceList() {
      taskManageApi.getServiceList().then((res) => {
        this.serverList = res.data.data;
        this.triggerForm = {
          ...this.triggerForm,
          jobGroup: [this.serverList[0].id],
        };
        this.remoteMethod();
      });
    },

    release(row) {
      api.subscribe({ id: row.id }).then((res) => {});
    },
    subscribe(data) {
      this.dialogType = "subscribe";
      this.dialogTitle = "订阅";
      this.triggerForm = {
        jobGroup: [],
        executorHandler: [],
      };
      this.currentData = { ...data };
      this.getServiceList();
    },
    confirmTrigger() {
      const data = this.currentData;
      if (this.dialogType === "send") {
        if (this.triggerForm.executorParam) {
          try {
            const executorParam = JSON.parse(this.triggerForm.executorParam);
          } catch (err) {
            this.$message.error("请输入正确的JSON格式");
            return;
          }
        }
        api
          .sending({
            messageCode: data.messageCode,
            executorParam: this.triggerForm.executorParam,
          })
          .then(() => {
            this.triggerVisible = false;
            this.triggerForm.executorParam="";
            this.$message.success("发送成功");
            this.getPage();
          });
      }
      if (this.dialogType === "subscribe") {
        api
          .mount({
            id: data.id,
            executorHandlers: this.triggerForm.executorHandler,
          })
          .then(() => {
            this.triggerVisible = false;
            this.subscribeVisible = false;

            this.triggerForm = {
              jobGroup: [],
            };
            this.$message.success("订阅成功");
            this.getPage();
          });
      }
    },
    send(data) {
      this.dialogType = "send";
      this.dialogTitle = "发送";
      this.triggerVisible = true;
      this.triggerForm = {
        executorParam:data.executorParam
      };
      this.currentData = { ...data };
    },
    // 向抽屉中添加tab页 根据 oid 去重
    addToTabsList(title, row, component, type) {
      let ids = this.tabsList.map((item) => item.row.id + "-" + item.component);
      if (!ids.includes(row.id + "-" + component)) {
        this.tabsList.push({ title, row, component, type });
      }
      this.visible = true;
    },
    getPage() {
      this.tableData = [];
      api
        .getList({
          start: this.page.currentPage,
          length: this.page.pageSize,
          ...this.queryForm,
        })
        .then((res) => {
          let { recordsTotal, data } = res.data;
          this.page.total = recordsTotal;
          this.tableData = data;
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getPage();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getPage();
    },
  },
  mounted() {
    this.getPage();
    this.$nextTick(() => {
      // 表格错位解决方法
      this.$refs.crud.refreshTable();
    });
  },
};
</script>

<style scoped lang="scss">
.header-search {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: nowrap;

  .form-item-wrap {
    width: 300px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: nowrap;

    $sp: 100px;

    > span {
      display: inline-block;
      width: $sp;
      line-height: 33px;
      text-align: right;
    }

    ::v-deep.el-select {
      width: calc(100% - #{$sp});
    }
  }
}
</style>
